package com.liang.sql;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Map;
import com.google.common.collect.Maps;
import com.liang.kit.ReflectUtil;

public class SqlTemplate<T extends MyBatis> {

    public String save(T obj) {  
    	StringBuilder sql=new StringBuilder("insert into "+obj.tablename()+"(");
    	sql.append(")");
    	sql.append(" values(");
    	sql.append(")");
        return sql.toString();  
    }  
      
    public String update(T obj) {  
    	StringBuilder sql=new StringBuilder("update "+obj.tablename()+" set ");
    	sql.append(" where "+obj.id()+"=#{"+obj.realId()+"}");
        return sql.toString();  
    }  
      
    public String delete(T obj) {  
    	StringBuilder sql=new StringBuilder();
    	sql.append("delete from "+obj.tablename()+" where "+obj.id()+"=#{"+obj.realId()+"}");
        return sql.toString();  
    } 
    public String deleteBatch(T obj,Map<String, String[]> map) {  
    	String[] ids=map.get("ids");
    	StringBuilder sql=new StringBuilder();
    	sql.append("delete from "+obj.tablename()+" where "+obj.id()+"in(");
		for(int i=0;i<ids.length;i++){
			if(i==ids.length){
				sql.append(ids[i]+")");
			}else{
				sql.append(ids[i]+",");
			}
		}
        return sql.toString();  
    } 
    public String updateBatch(T obj,Map<String, String[]> map) {  
    	String[] ids=map.get("ids");
    	StringBuilder sql=new StringBuilder();
    	sql.append("update "+obj.tablename()+" set status=0 where "+obj.id()+"in(");
		for(int i=0;i<ids.length;i++){
			if(i==ids.length){
				sql.append(ids[i]+")");
			}else{
				sql.append(ids[i]+",");
			}
		}
        return sql.toString();  
    } 
	public static Map<String,Object> describe(Object obj){
		Map<String,Object> map=Maps.newHashMap();
		Class<?> clazz = obj.getClass();
		Field[] fields = clazz.getDeclaredFields();
		for (int i = 0; i < fields.length; i++) {
			Field field=fields[i];
			field.setAccessible(true);
			if ((field.getModifiers() & Modifier.STATIC) == 0) {
				if(field.isAnnotationPresent(FieldBind.class)){
					Object value=null;
					try {
						value = field.get(obj);
					} catch (Exception e) {
						e.printStackTrace();
					} 
					if(field.getType().getSuperclass()==MyBatis.class){
						value=ReflectUtil.invokeGetter(obj, field.getName()+".id");
					}
					map.put(field.getAnnotation(FieldBind.class).fieldName(), value);
				}
			}
			field.setAccessible(false);
		}
		return map;
	}
}
